package org.example.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpBusinessHandler2 extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception {
        HttpMethod method = httpRequest.method();
        System.out.println("请求方法：" + method.name());
        String uri = httpRequest.uri();
        System.out.println("请求地址：" + uri);

        Map<String, Object> map = HttpProtocolHelper.parseFromUri(uri);
        for (Map.Entry<String, Object> mapItem : map.entrySet()) {
            System.out.printf(mapItem.getKey() + "=" + mapItem.getValue());
        }

        ByteBuf byteBuf = httpRequest.content();
        byte[] contents = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(contents);
        System.out.println("请求内容：" + new String(contents));
        HttpHeaders headers = httpRequest.headers();
        for (Map.Entry<String, String> entry : headers.entries()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }

        // 需要构造一个httpresponse
        HttpVersion version = httpRequest.protocolVersion();
        ctx.channel().attr(HttpProtocolHelper.HTTPVERSION_KEY).set(version);

        String responseContent = "{\"ServerName\":\"NettyServer\"}";
        HttpProtocolHelper.sendJsonContent(responseContent, ctx);
    }
}
